<?php
    $DEBUG = false;
    include_once "classes/User.php";
    session_start();
    include_once "session.php";
    if (!isLoggedIn()) {
        exit();
    }
    
    if ($_SESSION['User']->UserType == "Customer") { //Invalid privileges!
        exit();
    }
    
    if (!isset($_POST["action"])) {
        exit();
    }
    
    $arr = array();
    $arr["Success"] = 0;
    include_once "db/db_cse305.php";
    
    if ($_POST["action"] == "new") {
        if (!isset($_POST["form"])) {
            $arr["Msg"] = "No form data.";
            echo json_encode($arr);
            exit();
        }
        $d = $_POST["form"];
        
        if (!is_array($d) || count($d) != 18) {
            $arr["Msg"] = "Incorrect form data length.";
            echo json_encode($arr);
            exit();
        }
        for ($i = 0;$i < 12;$i++) {
            if ($i == 3) continue;
            if ($d[$i] == "") {
                $arr["Msg"] = "Missing field " . $i . ".";
                echo json_encode($arr);
                exit(); 
            }
        }
        
        
        if ($d[11] != "Customer" && $d[11] != "Representative" && $d[11] != "Manager") {
            $arr["Msg"] = "Missing field 11.";
            echo json_encode($arr);
            exit();
        }
        if ($d[11] == "Customer") {
            if ($d[12] == "" || $d[14] == "") { 
                $arr["Msg"] = "Missing customer field.";
                echo json_encode($arr);
                exit(); 
            }
        } else {
            if ($d[15] == "" || $d[16] == "" || $d[17] == "") { 
                $arr["Msg"] = "Missing employee field.";
                echo json_encode($arr);
                exit(); 
            }
        }
        
        $UserPriv = $_SESSION['User']->UserType;
        if ($UserPriv == 'Representative' && ($d[11] == "Representative" || $d[11] == "Manager")) {
            
            $arr["Msg"] = "Only managers can add new managers or new representatives.";
            echo json_encode($arr);
            exit(); 
        }
        
        if (strlen($d[0]) < 5 || strlen($d[0]) > 20) {
            $arr["Msg"] = "User name too long or short.";
            echo json_encode($arr);
            exit();
        }
        $query = sprintf("SELECT * FROM users WHERE UserName = '%s'", mysql_real_escape_string($d[0]));
        $result = mysql_query($query) or die(mysql_error());
        if (mysql_num_rows($result) > 0) {
            $arr["Msg"] = "User name is already taken.";
            echo json_encode($arr);
            exit();
        }
        if (strlen($d[1]) < 5 || strlen($d[1]) > 20) {
            $arr["Msg"] = "Password too long or short.";
            echo json_encode($arr);
            exit();
        }
        if ($d[1] != $d[2]) {
            $arr["Msg"] = "Passwords don't match.";
            echo json_encode($arr);
            exit();
        }
        if ($d[3] != "") {
            if (!is_numeric($d[3]) || $d[3] < 0 || $d[3] > 999999999) {
                $arr["Msg"] = "Invalid user ID.";
                echo json_encode($arr);
                exit();
            }
            $d[3] = floor($d[3]); //If user did something stupid, truncate the number.
            $query = sprintf("SELECT * FROM users WHERE UserId = '%d'", mysql_real_escape_string($d[3]));
            $result = mysql_query($query) or die(mysql_error());
            if (mysql_num_rows($result) > 0) {
                $arr["Msg"] = "User ID is already taken.";
                echo json_encode($arr);
                exit();
            }
        }
        if (strlen($d[4]) > 30) {
            $arr["Msg"] = "First name too long.";
            echo json_encode($arr);
            exit();
        }
        if (strlen($d[5]) > 30) {
            $arr["Msg"] = "Last name too long.";
            echo json_encode($arr);
            exit();
        }
        if (strlen($d[6]) > 75) {
            $arr["Msg"] = "Address too long.";
            echo json_encode($arr);
            exit();
        }
        if (strlen($d[7]) > 50) {
            $arr["Msg"] = "City too long.";
            echo json_encode($arr);
            exit();
        }
        if (strlen($d[8]) != 2) {
            $arr["Msg"] = "Invalid state.";
            echo json_encode($arr);
            exit();
        }
        $states = array("AL", "AK", "AZ", "AR", "CA", "CO", "CT", "DE", "DC", "FL", "GA", "HI", "ID", "IL", "IN", "IA", "KS", "KY", "LA", "ME", "MD", "MA", "MI", "MN", "MS", "MO", "MT", "NE", "NV", "NH", "NJ", "NM", "NY", "NC", "ND", "OH", "OK", "OR", "PA", "RI", "SC", "SD", "TN", "TX", "UT", "VT", "VA", "WA", "WV", "WI", "WY");
        if (!in_array($d[8], $states)) {
            $arr["Msg"] = "Unknown state.";
            echo json_encode($arr);
            exit();
        }
        if (strlen($d[9]) != 5 || !is_numeric($d[9]) || !isAllNumbers($d[9])) {
            $arr["Msg"] = "Invalid zip code.";
            echo json_encode($arr);
            exit();
        }
        if (strlen($d[10]) != 12 || $d[10][3] != '-' || $d[10][7] != '-' || !isTelNum($d[10])) {
            $arr["Msg"] = "Invalid telephone number.";
            echo json_encode($arr);
            exit();
        }
        
        if ($d[11] == "Customer") {
            if (!checkEmail($d[12])) {
                $arr["Msg"] = "Invalid email address.";
                echo json_encode($arr);
                exit();
            }
            if ($d[13] == "") {
                if (!is_numeric($d[13]) || $d[13] < 0 || $d[13] > 1000000) {
                    $arr["Msg"] = "Invalid customer rating.";
                    echo json_encode($arr);
                    exit();
                }
                $d[13] = floor($d[13]);
            }
            if (!checkCCN($d[14])) {
                $arr["Msg"] = "Invalid credit card number.";
                echo json_encode($arr);
                exit();
            }
        } else {
            if (!is_numeric($d[15]) || strlen($d[15]) != 9 || !isAllNumbers($d[15])) {
                $arr["Msg"] = "Invalid social security number.";
                echo json_encode($arr);
                exit();
            }
            if (!validDate($d[16])) {
                $arr["Msg"] = "Invalid employee start date.";
                echo json_encode($arr);
                exit();
            }
            if (!is_numeric($d[17])) {
                $arr["Msg"] = "Invalid employee hourly rate.";
                echo json_encode($arr);
                exit();
            }
            $d[17] = floor($d[17]);
        }
        
        //Validation done, insert new user.
        $salt = createSalt();
        $query = null;
        if ($d[3] == "") {
            $query = sprintf("INSERT INTO `users` (`UserName`,`UserType`,`Password`,`Salt`,`FirstName`,`LastName`,`Address`,`City`,`State`,`ZipCode`,`TelephoneNumber`) VALUES ('%s','%s', %s,'%s','%s','%s','%s','%s','%s','%05d','%s')",
                mysql_real_escape_string($d[0]),
                mysql_real_escape_string($d[11]),
                "SHA1(CONCAT('" . mysql_real_escape_string($d[1]) . "', '". $salt."'))",
                $salt,
                mysql_real_escape_string($d[4]),
                mysql_real_escape_string($d[5]),
                mysql_real_escape_string($d[6]),
                mysql_real_escape_string($d[7]),
                mysql_real_escape_string($d[8]),
                $d[9],
                mysql_real_escape_string($d[10])
            );
        } else {
            $query = sprintf("INSERT INTO `users` (`UserId`,`UserName`,`UserType`,`Password`,`Salt`,`FirstName`,`LastName`,`Address`,`City`,`State`,`ZipCode`,`TelephoneNumber`) VALUES (%d,'%s', '%s', %s, '%s','%s','%s','%s','%s','%s','%05d','%s')",
                mysql_real_escape_string($d[3]),   
                mysql_real_escape_string($d[0]),
                mysql_real_escape_string($d[11]),
                "SHA1(CONCAT('" . mysql_real_escape_string($d[1]) . "', '". $salt."'))",
                $salt,
                mysql_real_escape_string($d[4]),
                mysql_real_escape_string($d[5]),
                mysql_real_escape_string($d[6]),
                mysql_real_escape_string($d[7]),
                mysql_real_escape_string($d[8]),
                $d[9],
                mysql_real_escape_string($d[10])
            );
        }
        $result = mysql_query($query) or die(mysql_error());
        
        // Do this instead of mysql_insert_id to avoid race conditions. 
        $query = sprintf("SELECT `UserId` FROM `users` WHERE `UserName` = '%s'", mysql_real_escape_string($d[0]));
        $result = mysql_query($query) or die(mysql_error());
        $generatedID = null;
        while ($row = mysql_fetch_array($result)) {
            $generatedID = $row["UserId"];
        }
        
        if ($d[11] == "Customer") {
            $query = sprintf("INSERT INTO `customer` (`UserID`, `EmailAddress`, `Rating`, `CreditCardNumber`) VALUES (%d, '%s', %d, '%s')",
                $generatedID,
                mysql_real_escape_string($d[12]),
                mysql_real_escape_string($d[13]),
                mysql_real_escape_string($d[14])
            );
        } else {
            $query = sprintf("INSERT INTO `employees` (`UserID`, `SSN`, `StartDate`, `HourlyRate`) VALUES (%d, %d, '%s', %d)",
                $generatedID,
                mysql_real_escape_string($d[15]),
                mysql_real_escape_string($d[16]),
                mysql_real_escape_string($d[17])
            );
        }
        $result = mysql_query($query) or die(mysql_error());
        $arr["Success"] = 1;
        
        
        //EDIT LOAD
    } else if ($_POST["action"] == "edit_load") {
        $arr["Success"] = 0;
        if (!isset($_POST["uid"])) {
            $arr["Msg"] = "No UID data.";
            echo json_encode($arr);
            exit();
        }
        $uid = $_POST["uid"];
        if (!is_numeric($uid) || !isAllNumbers($uid)) {
            $arr["Msg"] = "Invalid UID format.";
            echo json_encode($arr);
            exit();
        }
        
        $editable = array("UserType", "Password", "FirstName", "LastName", "Address", "City", "State", "ZipCode", "TelephoneNumber");
        $alias =    array("User Type", "Password", "First Name", "Last Name", "Address", "City", "State", "Zip Code", "Telephone Number");
        $editVals = array();
        
        $query = sprintf("SELECT * FROM users WHERE UserId = %d", mysql_real_escape_string($uid));
        $result = mysql_query($query) or die(mysql_error());
        if ($row = mysql_fetch_array($result)) {
            //Uncomment these lines to hide Manager/Representative information from Representatives.
//            if (($row["UserType"] == 'Manager' || $row["UserType"] == 'Representative') && $_SESSION['User']->UserType != 'Manager') {
//                $arr["Msg"] = "You don't have permissions to edit non-customer information.";
//                echo json_encode($arr);
//                exit();
//            }
            for ($i = 0;$i < count($editable);$i++) {
                $editVals[] = $row[$editable[$i]];
            }
        } else {
            $arr["Msg"] = "User " . $uid . " not found.";
            echo json_encode($arr);
            exit(); //User not found.
        }
        
        $properties = array();
        $properties[] = array("FirstName", "First Name", $editVals[2]);
        $properties[] = array("LastName", "Last Name", $editVals[3]);
        $properties[] = array("Password", "Password", "");
        $properties[] = array("Address", "Address", $editVals[4]);
        $properties[] = array("City", "City", $editVals[5]);
        $properties[] = array("State", "State", $editVals[6]);
        $properties[] = array("ZipCode", "Zip Code", $editVals[7]);
        $properties[] = array("TelephoneNumber", "Telephone #", $editVals[8]);
        
        if ($editVals[0] == "Customer") { //Customers cannot change user type
            $query = sprintf("SELECT * FROM customer WHERE UserID = %d", mysql_real_escape_string($uid));
            $result = mysql_query($query) or die(mysql_error());
            if ($row = mysql_fetch_array($result)) {
                $properties[] = array("EmailAddress", "Email", $row["EmailAddress"]);
                $properties[] = array("Rating", "Rating", $row["Rating"]); 
                $properties[] = array("CreditCardNumber", "Credit Card #", $row["CreditCardNumber"]);
            } else {
                $arr["Msg"] = "Customer " . $uid . " not found.";
                echo json_encode($arr);
                exit(); //User not found.
            }
        } else if ($editVals[0] == "Representative" || $editVals[0] == "Manager") {
            $query = sprintf("SELECT * FROM employees WHERE UserID = %d", mysql_real_escape_string($uid));
            $result = mysql_query($query) or die(mysql_error());
            if ($row = mysql_fetch_array($result)) {
                $properties[] = array("UserType", "User Type", $editVals[0]);
                $properties[] = array("SSN", "Social Security Number", $row["SSN"]);
                $properties[] = array("StartDate", "Start Date", $row["StartDate"]);
                if ($_SESSION['User']->UserType == 'Manager') //Only managers can view hourly rates
                    $properties[] = array("HourlyRate", "Hourly Rate", $row["HourlyRate"]);
            } else {
                $arr["Msg"] = "Employee " . $uid . " not found.";
                echo json_encode($arr);
                exit(); //User not found.
            }
        }
        $arr["Success"] = 1;
        $arr["Properties"] = $properties;
    } else if ($_POST["action"] == "edit") {
        $arr["Success"] = 0;
        if (!isset($_POST["d"]) || !isset($_POST["f"]) || !isset($_POST["uid"])) {
            $arr["Msg"] = "Missing data.";
            echo json_encode($arr);
            exit();
        }
        $d = $_POST["d"];
        $f = $_POST["f"];
        $uid = $_POST["uid"];
        if ($d == "" || $f == "" || $uid == "") {
            $arr["Msg"] = "Missing data.";
            echo json_encode($arr);
            exit();
        }
        if (!is_numeric($uid) || !isAllNumbers($uid)) {
            $arr["Msg"] = "Invalid UID format.";
            echo json_encode($arr);
            exit();
        }
        
        
        //Check permissions first
        $query = sprintf("SELECT * FROM users WHERE UserId = %d", mysql_real_escape_string($uid));
        $result = mysql_query($query) or die(mysql_error());
        $EditUserType = null;
        if ($row = mysql_fetch_array($result)) {
            $EditUserType = $row["UserType"];
        } else {
            $arr["Msg"] = "User " . $uid . " not found.";
            echo json_encode($arr);
            exit(); //User not found.
        }
        
        if ($_SESSION['User']->UserType != 'Manager' && ($EditUserType == "Manager" || $EditUserType == "Representative")) {
            $arr["Msg"] = "You don't have permissions to edit non-customer information.";
            echo json_encode($arr);
            exit();
        }
        
        if ($f == "FirstName") {
            if (strlen($d) > 30) {
                $arr["Msg"] = "First name too long.";
                echo json_encode($arr);
                exit();
            }
            $query = sprintf("UPDATE users SET FirstName = '%s' WHERE UserId = %d", mysql_real_escape_string($d), mysql_real_escape_string($uid));
        } else if ($f == "LastName") {
            if (strlen($d) > 30) {
                $arr["Msg"] = "Last name too long.";
                echo json_encode($arr);
                exit();
            }
            $query = sprintf("UPDATE users SET LastName = '%s' WHERE UserId = %d", mysql_real_escape_string($d), mysql_real_escape_string($uid));
        } else if ($f == "Password") {
            if (strlen($d) < 5 || strlen($d) > 20) {
                $arr["Msg"] = "Password too long or short.";
                echo json_encode($arr);
                exit();
            }
            $salt = createSalt();
            $query = sprintf("UPDATE users SET Password = %s, Salt = '%s' WHERE UserId = %d", 
                    "SHA1(CONCAT('" . mysql_real_escape_string($d) . "', '". $salt."'))", $salt, mysql_real_escape_string($uid));
        } else if ($f == "Address") {
            if (strlen($d) > 75) {
                $arr["Msg"] = "Address too long.";
                echo json_encode($arr);
                exit();
            }
            $query = sprintf("UPDATE users SET Address = '%s' WHERE UserId = %d", mysql_real_escape_string($d), mysql_real_escape_string($uid));
        } else if ($f == "City") {
            if (strlen($d) > 50) {
                $arr["Msg"] = "City too long.";
                echo json_encode($arr);
                exit();
            }
            $query = sprintf("UPDATE users SET City = '%s' WHERE UserId = %d", mysql_real_escape_string($d), mysql_real_escape_string($uid));
        } else if ($f == "State") {
            if (strlen($d) != 2) {
                $arr["Msg"] = "Invalid state (Use 2 letter initial).";
                echo json_encode($arr);
                exit();
            }
            $states = array("AL", "AK", "AZ", "AR", "CA", "CO", "CT", "DE", "DC", "FL", "GA", "HI", "ID", "IL", "IN", "IA", "KS", "KY", "LA", "ME", "MD", "MA", "MI", "MN", "MS", "MO", "MT", "NE", "NV", "NH", "NJ", "NM", "NY", "NC", "ND", "OH", "OK", "OR", "PA", "RI", "SC", "SD", "TN", "TX", "UT", "VT", "VA", "WA", "WV", "WI", "WY");
            if (!in_array($d, $states)) {
                $arr["Msg"] = "Unknown state.";
                echo json_encode($arr);
                exit();
            }
            $query = sprintf("UPDATE users SET State = '%s' WHERE UserId = %d", mysql_real_escape_string($d), mysql_real_escape_string($uid));
        
        } else if ($f == "ZipCode") {
            if (strlen($d) != 5 || !is_numeric($d) || !isAllNumbers($d)) {
                $arr["Msg"] = "Invalid zip code.";
                echo json_encode($arr);
                exit();
            }
            $query = sprintf("UPDATE users SET ZipCode = '%s' WHERE UserId = %d", mysql_real_escape_string($d), mysql_real_escape_string($uid));
        } else if ($f == "TelephoneNumber") {
            if (strlen($d) != 12 || $d[3] != '-' || $d[7] != '-' || !isTelNum($d)) {
                $arr["Msg"] = "Invalid telephone number.";
                echo json_encode($arr);
                exit();
            }
            $query = sprintf("UPDATE users SET TelephoneNumber = '%s' WHERE UserId = %d", mysql_real_escape_string($d), mysql_real_escape_string($uid));
        } else {
            if ($EditUserType == "Manager" || $EditUserType == "Representative") {
                //Check again to be safe - Only managers can change employee info.
                if ($_SESSION['User']->UserType != 'Manager') {
                    $arr["Msg"] = "Insufficient privileges.";
                    echo json_encode($arr);
                    exit();
                }
                if ($f == "UserType") {
                    if ($d != 'Manager' && $d =! 'Representative') {
                        $arr["Msg"] = "Invalid UserType.";
                        echo json_encode($arr);
                        exit();
                    }
                    $query = sprintf("UPDATE users SET UserType = '%s' WHERE UserId = %d", mysql_real_escape_string($d), mysql_real_escape_string($uid));
                } else if ($f == "SSN") {
                    if (!is_numeric($d) || strlen($d) != 9 || !isAllNumbers($d)) {
                        $arr["Msg"] = "Invalid social security number.";
                        echo json_encode($arr);
                        exit();
                    }
                    $query = sprintf("UPDATE employees SET SSN = '%s' WHERE UserId = %d", mysql_real_escape_string($d), mysql_real_escape_string($uid));
                
                } else if ($f == "StartDate") {
                    if (!validDate($d)) {
                        $arr["Msg"] = "Invalid employee start date.";
                        echo json_encode($arr);
                        exit();
                    }
                    $query = sprintf("UPDATE employees SET StartDate = '%s' WHERE UserId = %d", mysql_real_escape_string($d), mysql_real_escape_string($uid));
                
                } else if ($f == "HourlyRate") {
                    if (!is_numeric($d)) {
                        $arr["Msg"] = "Invalid employee hourly rate.";
                        echo json_encode($arr);
                        exit();
                    }
                    $query = sprintf("UPDATE employees SET HourlyRate = %d WHERE UserId = %d", mysql_real_escape_string($d), mysql_real_escape_string($uid));
                } else {
                    $arr["Msg"] = "Invalid Field " . $f;
                    echo json_encode($arr);
                    exit();
                }
            } else if ($EditUserType == "Customer") {
                if ($f == "EmailAddress") {
                    if (!checkEmail($d)) {
                        $arr["Msg"] = "Invalid email address.";
                        echo json_encode($arr);
                        exit();
                    }
                    $query = sprintf("UPDATE customer SET EmailAddress = '%s' WHERE UserId = %d", mysql_real_escape_string($d), mysql_real_escape_string($uid));
                } else if ($f == "Rating") {
                    if (!is_numeric($d) || $d < 0 || $d > 1000000) {
                        $arr["Msg"] = "Invalid customer rating.";
                        echo json_encode($arr);
                        exit();
                    }
                    $d = floor($d);
                    $query = sprintf("UPDATE customer SET Rating = %d WHERE UserId = %d", mysql_real_escape_string($d), mysql_real_escape_string($uid));
                } else if ($f == "CreditCardNumber") {
                    if (!checkCCN($d)) {
                        $arr["Msg"] = "Invalid credit card number.";
                        echo json_encode($arr);
                        exit();
                    }
                    $query = sprintf("UPDATE customer SET CreditCardNumber = '%s' WHERE UserId = %d", mysql_real_escape_string($d), mysql_real_escape_string($uid));
                } else {
                    $arr["Msg"] = "Invalid Field " . $f;
                    echo json_encode($arr);
                    exit();
                }
            } else {
                $arr["Msg"] = "Unknown DB UserType";
                echo json_encode($arr);
                exit();
            }
        }
        $result = mysql_query($query) or die(mysql_error());
        $arr["Success"] = 1;
    } else if ($_POST["action"] == "delete") {
        $arr["Success"] = 0;
        if (!isset($_POST["uid"])) {
            $arr["Msg"] = "Missing data.";
            echo json_encode($arr);
            exit();
        }
        $uid = $_POST["uid"];
        if ($uid == "") {
            $arr["Msg"] = "Missing data.";
            echo json_encode($arr);
            exit();
        }
        if (!is_numeric($uid) || !isAllNumbers($uid)) {
            $arr["Msg"] = "Invalid UID format.";
            echo json_encode($arr);
            exit();
        }
        
        $query = sprintf("SELET * FROM users WHERE UserId = %d", $uid);
        $result = mysql_query($query) or die(mysql_error());
        $DelUserType = "";
        if ($row = mysql_fetch_array($result)) {
            $DelUserType = $row["UserType"];
        } else {
            $arr["Msg"] = "User does not exist.";
        }
        
        if (($DelUserType == "Manager" || $DelUserType == 'Representative') && $_SESSION['User']->UserType != 'Manager') {
            $arr["Msg"] = "Only Managers can delete non-customers.";
        }
        
        $query = sprintf("DELETE FROM users WHERE UserId = %d", $uid);
        $result = mysql_query($query) or die(mysql_error());
        if (mysql_affected_rows() > 0) {
            $arr["Success"] = 1;
        } else {
            $arr["Msg"] = "Something went wrong (or user does not exist)... try again later.";
        }
    } else {
        exit();
    }
    echo json_encode($arr);

    
    
    function createSalt() {
        return md5(md5(uniqid(rand(), true)));
    }
    function checkEmail($v) {
        return preg_match('/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i', $v);
    }
    function checkCCN($v) {
        return preg_match('/^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6(?:011|5[0-9][0-9])[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\d{3})\d{11})$/', $v);
    }
    function validDate($v) {
        return preg_match('/^(19|20|21)\d\d[-](0[1-9]|1[012])[-](0[1-9]|[12][0-9]|3[01])$/', $v) && 
             checkdate(substr($v, 5, 2),substr($v, 8, 2),substr($v, 0, 4));
    }
    function isTelNum($v) {
        for ($i = 0;$i < strlen($v);$i++) {
            if ($i == 3 || $i == 7) continue;
            $t = is_numeric($v[$i]);
            if (!$t) return 0;
        }
        return 1;
    }
    function isAllNumbers($v) {
        for ($i = 0;$i < strlen($v);$i++) {
            $t = is_numeric($v[$i]);
            if (!$t) return 0;
        }
        return 1;
    }
?>
